# -*- coding: utf-8 -*-
# @Author: QX
# @File: AppTestRunner.py
import allure
import pytest

from core.globalContext import g_context
from examples.context import Context
from parse.YamlCaseParser import load_yaml_files, yaml_case_parser
from  extend.keywords import Keywords
from utils.DynamicTitle import dynamicTitle
from utils.VarRender import ReFresh


# class TestRunner():
#     def test_case_execute(self,get_readhdriver,caseinfo):
#         global driver
#         driver = get_readhdriver
#         setattr(Context, 'driver', driver)
#         # 生成测试用例的标题
#         # allure.dynamic.title(caseinfo['desc'])
#         dynamicTitle(caseinfo)
#         # 关键字的实例化
#         kd = Keywords(driver)
#         gc = g_context()
#         # 从测试用例中获得ddt的数据
#         local_context = caseinfo.get("context",{})
#         try:
#             #获得测试用例的操作步骤
#             steps = caseinfo.get('steps',None)
#             context = gc.show_dict()
#             print('context=====',context)
#             #把ddt的数据加载到渲染源中
#             context.update(local_context)
#             #获得所有的操作步骤名称和所有的操作步骤
#             for  step  in steps:
#                 step_name = list(step.keys())[0]
#                 step_value = list(step.values())[0]
#                 print('渲染前：',step_value)
#                 step_value = eval(ReFresh(step_value,context))
#                 print('渲染后：', step_value)
#
#                 with allure.step(step_name):
#                     #获得在关键字中调用的函数名
#                     def_name = step_value['关键字']
#                     #def_name是否在关键字文件keywords中存在，存在就调用，不存在就提示
#                     try:
#                         key_func = kd.__getattribute__(def_name)
#
#                     except Exception  as e:
#                         assert False,f"断言失败--没有找到关键字{e}"
#                 key_func(**step_value)
#         except Exception  as e:
#             assert False, f"断言失败--可能是代码报错{e}"
#         finally:
#             pass


# core/AppTestRunner.py
import allure
import pytest
from Appium_Python.core.globalContext import g_context
from Appium_Python.examples.context import Context
from Appium_Python.parse.YamlCaseParser import yaml_case_parser
from Appium_Python.pages.LoginPage import LoginPage
from Appium_Python.utils.DynamicTitle import dynamicTitle
from Appium_Python.utils.VarRender import ReFresh
from appium import webdriver

@pytest.fixture(scope="function")
def get_driver():
    dis = {
        "platformName": "Android",
        "appium:platformVersion": "9",
        "appium:appPackage": "com.tal.kaoyan",
        "appium:appActivity": ".ui.activity.SplashActivity",
        "appium:deviceName": "emulator-5554",
        "appium:automationName": "UIAutomator2",
        "appium:noReset": False,
        "newCommandTimeout": "3000"
    }
    driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', dis)
    setattr(Context, 'driver', driver)
    yield driver
    driver.quit()

class TestLogin:
    @pytest.mark.parametrize("caseinfo", yaml_case_parser("./examples/yaml_case")["case_infos"])
    def test_login_flow(self, get_driver, caseinfo):
        dynamicTitle(caseinfo)
        driver = get_driver
        login_page = LoginPage(driver)
        local_context = caseinfo.get("context", {})
        context = g_context().show_dict()
        context.update(local_context)

        for step in caseinfo.get("steps", []):
            step_name = list(step.keys())[0]
            step_value = list(step.values())[0]
            step_value = eval(ReFresh(step_value, context))

            with allure.step(step_name):
                func_name = step_value['关键字']
                try:
                    func = getattr(login_page, func_name)
                except AttributeError:
                    assert False, f"找不到关键字方法: {func_name}"
            func(**step_value)




if __name__ == '__main__':
    pytest.main(['-vs',__file__])


